import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'fluro_support_application.dart';

/// fluro的路由跳转工具类
class FSNavigate {
  /// 不需要页面返回值的跳转
  static push(BuildContext context, String path,
      {bool replace = false, bool clearStack = false}) {
    debugPrint('fs to path ::: ${path}');
    FocusScope.of(context).requestFocus(new FocusNode());
    FSApplication.router.navigateTo(context, path,
        replace: replace,
        clearStack: clearStack,
        transition: TransitionType.native);
  }

  ///
  static pushMap(
      BuildContext context, String path, Map<String, String> arguments,
      {bool replace = false, bool clearStack = false}) {
    if (arguments == null) {
      throw Exception("请正确设置需要携带到新页面的参数");
    }
    arguments.forEach((key, value) {
      path += '&${key}=${Uri.encodeComponent(value)}';
    });
    push(context, path.replaceFirst("&", "?", 0),
        replace: replace, clearStack: clearStack);
  }

  /// 需要页面返回值的跳转
  static pushResult(
      BuildContext context, String path, Function(Object) function,
      {bool replace = false, bool clearStack = false}) {
    debugPrint('fs to path ::: ${path}');
    FocusScope.of(context).requestFocus(new FocusNode());
    FSApplication.router
        .navigateTo(context, path,
            replace: replace,
            clearStack: clearStack,
            transition: TransitionType.native)
        .then((result) {
      // 页面返回result为null
      if (result == null) {
        return;
      }
      function(result);
    }).catchError((error) {
      print("$error");
    });
  }

  /// 需要页面返回值的跳转
  static pushMapResult(BuildContext context, String path,
      Map<String, String> arguments, Function(Object) function,
      {bool replace = false, bool clearStack = false}) {
    if (arguments == null) {
      throw Exception("请正确设置需要携带到新页面的参数");
    }
    arguments.forEach((key, value) {
      path += '&${key}=${Uri.encodeComponent(value)}';
    });
    pushResult(context, path.replaceFirst("&", "?", 0), function,
        replace: replace, clearStack: clearStack);
  }

  /// 返回
  static void goBack(BuildContext context) {
    FocusScope.of(context).requestFocus(new FocusNode());
    Navigator.pop(context);
  }

  /// 带参数返回
  static void goBackWithParams(BuildContext context, result) {
    FocusScope.of(context).requestFocus(new FocusNode());
    Navigator.pop(context, result);
  }
}
